// pages/meal/meal.js
var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    mealList: [],
    mtype: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      mtype: options.mtype
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.initApp()
  },

  /**
   * init
   */
  initApp: function() {
    let that = this
    wx.showLoading({
      title: app.globalData.loadText,
    })
    wx.request({
      url: app.globalData.hostAPI + '/v1/setmeal/index?type=' + that.data.mtype,
      success: res => {
        that.setData({
          mealList: res.data.data.setmeal
        })
        wx.hideLoading()
      }
    })
  },

  /**
   * 
   */
  paymentClick: function(e) {
    let that = this,
        mid = e.currentTarget.dataset.tid,
        payInfo, tradeNo
    wx.showLoading({
      mask: true,
      title: app.globalData.loadText,
    })
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/v1/wxpay/setmeal?access_token=' + accessToken,
        data: {
          setmeal_id: mid
        },
        success: res => {
          console.log(res)
          if(res.data.status === 1) {
            payInfo = res.data.data
            tradeNo = res.data.data.out_trade_no
            if (payInfo.appId) {
              //支付
              wx.requestPayment({
                timeStamp: payInfo.timeStamp,
                nonceStr: payInfo.nonceStr,
                package: payInfo.package,
                signType: payInfo.signType,
                paySign: payInfo.paySign,
                success: res => {
                  wx.showModal({
                    title: '提示',
                    content: '购买成功',
                    success: res => {
                      if (res.confirm) {
                        wx.reLaunch({
                          url: '/pages/success/success'
                        })
                      }
                    }
                  })
                }
              })
            } else {
              //余额抵扣
              wx.hideLoading()
              wx.showModal({
                title: '提示',
                content: res.data.msg,
                success: res => {
                  if(res.confirm) {
                    wx.navigateTo({
                      url: '/pages/success/success'
                    })
                  }
                }
              })
            }
            wx.hideLoading()
          }
        }
      })
    })
  },

  onShareAppMessage: function(res) {
    return {
      title: '买套餐，更合适',
    }
  }
})